import Router from 'koa-router'
import {
  resolve
} from 'path'
import glob from 'glob' // 引入glob库
import _ from 'lodash' // 引入lodash中间库

export let routersMap = new Map() // 
export const symbolPrefix = Symbol('prefix') // 利用Symbol生成原始数据类型Symbol，表示独一无二的值
export const isArray = arr => _.isArray(arr) ? arr : [arr]
export const normalizePath = path => path.startsWith('/') ? path : `/${path}`

export default class Route {

  /**
   * 构造器函数
   * @param {Object} app 传入web实例
   * @param {String} apiPath  路由路径文件夹
   */
  constructor(app, apiPath) {
    this.app = app
    this.router = new Router()
    this.apiPath = apiPath
  }

  /**
   * 初始化router
   */
  init() {
    // require所有的路由模块
    glob.sync(resolve(this.apiPath, './*.js')).forEach(require)

    for (let [conf, controller] of routersMap) {
      const controllers = isArray(controller)
      let prefixPath = conf.target[symbolPrefix]
      if (prefixPath) {
        prefixPath = normalizePath(prefixPath)
      }

      const routerPath = prefixPath + conf.path
      this.router[conf.method](routerPath, ...controllers)
    }

    // 调用router
    this.app.use(this.router.routes())
    this.app.use(this.router.allowedMethods())
  }
}

export const router = conf => (target, key, desc) => {
  conf.path = normalizePath(conf.path)
  routersMap.set({
    target: target,
    ...conf
  }, target[key])
}

export const controller = path => target => target.prototype[symbolPrefix] = path

export const get = path => router({
  method: 'get',
  path: path
})
export const post = path => router({
  method: 'post',
  path: path
})
export const put = path => router({
  method: 'put',
  path: path
})
export const del = path => router({
  method: 'del',
  path: path
})
export const all = path => router({
  method: 'all',
  path: path
})
